<template>
	<el-container>
		<el-header>
			<div class="left-panel">
				<el-button-group>
					<el-button type="primary" icon="el-icon-box" @click="modelCreate">创建模型</el-button>
					<!--el-button type="info" plain icon="el-icon-document-copy" @click="cloneModel" v-if="selection.length!=0">克隆模型</el-button>
					<el-button type="info" plain icon="el-icon-scale-to-original" @click="viewCreate">创建视图</el-button>
					<el-button type="info" plain icon="el-icon-tickets" @click="reversalModel">模型反转</el-button>
					<el-button type="info" plain icon="el-icon-refresh" @click="syncTable">同步表结构</el-button-->
					<el-button type="danger" icon="el-icon-delete" :disabled="selection.length==0" @click="batch_del" v-if="selection.length>0">删除</el-button>
				</el-button-group>
			</div>
			<div class="right-panel">
				<div class="right-panel-search">
					<el-input v-model="keyword" placeholder="模型名称" clearable></el-input>
					<el-button type="primary" icon="el-icon-search" @click="upsearch"></el-button>
				</div>
			</div>
		</el-header>
		<el-main class="nopadding">
			<jdTable ref="table" :apiObj="apiObj" :params="params" row-key="id" @selection-change="selectionChange" stripe>
				<el-table-column type="selection" width="50" align="center"></el-table-column>
				<el-table-column label="类型" prop="modelType" width="80" align="center">
					<template #default="scope">
						<span v-if="scope.row.modelType === 'model'">
							<jd-icon-model style="width: 30px;"/>
						</span>
						<span v-if="scope.row.modelType === 'view'">
							<jd-icon-view style="width: 30px;"/>
						</span>
						<span v-if="scope.row.modelType === 'reversal'">
							<jd-icon-reversal style="width: 30px;"/>
						</span>
						<!-- <DictTag :options="typeDict" :value="scope.row.modelType"></DictTag> -->
					</template>
				</el-table-column>
				<el-table-column label="模型名称" prop="tableComment" min-width="150"></el-table-column>
				<el-table-column label="数据表名" prop="tableName" min-width="150"></el-table-column>
				<el-table-column label="字段数" prop="tableFields" width="150" align="center">
					<template #default="scope">
						共 {{ JSON.parse(scope.row.tableFields).length }} 个
					</template>
				</el-table-column>
				<el-table-column label="模型描述" prop="tableExplain" min-width="200"></el-table-column>
				<el-table-column label="创建时间" prop="createTime" width="180"></el-table-column>
				<el-table-column label="操作" fixed="right" align="center" width="150">
					<template #default="scope">
						<el-button-group>
							<el-button text type="primary" :loading="editLoading" @click="table_edit(scope.row, scope.$index)" class="button">编辑</el-button>
							<el-popconfirm title="确定要删除吗？" @confirm="table_del(scope.row, scope.$index)">
								<template #reference>
									<el-button text type="primary" class="button">删除</el-button>
								</template>
							</el-popconfirm>
						</el-button-group>
					</template>
				</el-table-column>
			</jdTable>
		</el-main>
	</el-container>

	<create-dialog v-if="dialog.modelCreate" @close="refresh" ref="createDialog"  @success="handleSaveSuccess" @closed="dialog.modelCreate=false"></create-dialog>
	<view-dialog v-if="dialog.viewCreate" @close="refresh" ref="viewDialog"  @success="handleSaveSuccess" @closed="dialog.viewCreate=false"></view-dialog>
	<reversal-dialog v-if="dialog.modelReversal" @close="refresh" ref="reversalDialog"  @success="handleSaveSuccess" @closed="dialog.modelReversal=false"></reversal-dialog>

</template>

<script>
	import Sortable from 'sortablejs'
	import createDialog from './create';
	import viewDialog from './view';
	import reversalDialog from './reversal';

	export default {
		name: 'dataModel',
		components: {
			createDialog,
			viewDialog,
			reversalDialog
		},
		data() {
			return {
				dialog: {
					modelCreate: false,
					viewCreate: false,
					modelReversal: false
				},
				apiObj: null,
				selection: [],
				params: {
					keyword: null,
					appId:null,
				},
				keyword: null,
				timer: "", //定义一个定时器
        		nowTime: "",
				form:{
					appName: "",
					appType: ""
				},
				cardNum: 1,
				appList: [],
				// 类型字典
				typeDict:[],
				editLoading: false,
			}
		},
		mounted() {
			this.params.appId = this.$route.query.appId
			this.getDict();
			this.rowDrop();
			this.getModelList();
			// 自动展开菜单
			this.$store.commit('TOGGLE_IsCollapse', false);
		},
		methods: {
			// 模型列表
			async getModelList(){
				this.apiObj = this.$API.app.model.list;
			},
			// 创建模型
			modelCreate(){
				this.dialog.modelCreate = true;
				this.$nextTick(() =>{
					this.$refs.createDialog.open();
				})
			},
			// 克隆模型
			cloneModel(){

			},
			// 创建视图
			viewCreate(){
				this.dialog.viewCreate = true;
				this.$nextTick(() =>{
					this.$refs.viewDialog.open();
				})
			},
			// 模型反转
			reversalModel(){

			},
			// 同步表结构
			syncTable(){

			},

			//添加
			add(){
				this.dialog.save = true
				this.$nextTick(() => {
					this.$refs.saveDialog.open()
				})
			},
			//编辑
			async table_edit(row) {
				this.editLoading =true;
				// 根据模型ID获取模型详情
				let res = await this.$API.app.model.get.get(row.id);
				if (res.code == 200){
					this.dialog.modelCreate = true;
					this.$nextTick(() => {
						this.$refs.createDialog.open('edit').setData(res.data);
					})
					this.editLoading =false;
				}
			},
			//查看
			table_show(row){
				this.dialog.save = true
				this.$nextTick(() => {
					this.$refs.saveDialog.open('show').setData(row)
				})
			},
			//删除
			async table_del(row){
					let res = await this.$API.app.model.del.delete(row.id);
					if(res.code == 200){
						this.$refs.table.refresh()
						this.$message.success("删除成功")
					}else{
						this.$alert(res.msg, "提示", {type: 'error'})
					}
			},
			//批量删除
			async batch_del(){
				this.$confirm(`确定删除选中的 ${this.selection.length} 项吗？如果删除项中含有子集将会被一并删除`, '提示', {
					type: 'warning'
				}).then(async () => {
					let ids = this.selection.map((item) => item.id)
					let res = await this.$API.app.model.del.delete(ids);
					if (res.code === 200) {
						this.$refs.table.refresh()
						this.$message.success("删除成功")
					} else {
						this.$alert(res.msg, "提示", {type: 'error'})
					}
					const loading = this.$loading();
					loading.close();
				}).catch(() => {

				})
			},
			// 字典获取
			async getDict() {
				this.typeDict = await this.Dict.get("app_model_type");
			},
			//表格选择后回调事件
			selectionChange(selection){
				this.selection = selection;
			},
			//表格内开关
			changeSwitch(val, row){
				row.status = row.status == '1'?'0':'1'
				row.$switch_status = true;
				setTimeout(()=>{
					delete row.$switch_status;
					row.status = val;
					this.$message.success("操作成功")
				}, 500)
			},
			//搜索
			upsearch(){
				this.params.tableComment = this.keyword;
				this.$refs.table.refresh()
			},
			//根据ID获取树结构
			filterTree(id){
				var target = null;
				function filter(tree){
					tree.forEach(item => {
						if(item.id == id){
							target = item
						}
						if(item.children){
							filter(item.children)
						}
					})
				}
				filter(this.$refs.table.tableData)
				return target
			},
			//本地更新数据
			handleSaveSuccess(data, mode){
				if(mode=='add'){
					this.$refs.table.refresh()
				}else if(mode=='edit'){
					this.$refs.table.refresh()
				}
			},
			//行拖拽
			rowDrop(){
				const _this = this
				const tbody = this.$refs.table.$el.querySelector('.el-table__body-wrapper tbody')
				Sortable.create(tbody, {
					handle: ".move",
					animation: 300,
					ghostClass: "ghost",
					async onEnd({ newIndex, oldIndex }) {
						this.loading = true;
						const tableData = _this.$refs.table.tableData
						const currRow = tableData.splice(oldIndex, 1)[0]
						tableData.splice(newIndex, 0, currRow)

						// 字典数据排序
						let res = await _this.$API.app.model.changeSort.put(tableData);
						console.log(res)
					/*	if(res.code == 200){
							_this.$refs.table.tableData = [];
							_this.$refs.table.reload({dictType: _this.dictType});
							this.loading = false;
						}*/
					}
				})
			},
		}
	}
</script>

<style>
</style>
